<script>
import FriendItem from "@/components/friend/FriendItem.vue";
import AddFriend from "@/view/AddFriend.vue";
import HeadImage from "@/components/common/HeadImage.vue";
import GroupItem from "@/components/group/GroupItem.vue";
import GroupMember from "@/components/group/GroupMember.vue";
import FileUpload from "@/components/common/FileUpload.vue";
import AddGroupMember from "@/components/group/AddGroupMember.vue";
import {Dialog} from "vant";

export default {
  name: "Contacts",
  components: {
    FriendItem,
    AddFriend,
    HeadImage,
    GroupItem,
    GroupMember,
    FileUpload,
    AddGroupMember,
  },
  data() {
    return {
      active: 0,
      // friend
      showAddFriend: false,
      activeIdx: -1,
      userInfo: {},
      // group
      maxSize: 5 * 1024 * 1024,
      activeGroup: {},
      groupMembers: [],
      showAddGroupMember: false,
      rules: {
        name: [{
          required: true,
          message: 'Please input the group chat name',
          trigger: 'blur'
        }]
      }
    };
  },
  methods: {
    onChange(name, title) {
      if(name === 'friend') {
        console.log('1')
      } else {
        console.log('2')
      }
    },
    onShowAddFriend() {
      this.showAddFriend = true;
    },
    onCloseAddFriend() {
      this.showAddFriend = false;
    },
    onActiveItemFriend(friend, idx) {
      console.log('Click friend: ', friend)
      this.$store.commit("activeFriend", idx);
      this.activeIdx = idx
      this.loadUserInfo(friend, idx);
    },
    onDelItem(friend, idx) {
      Dialog.confirm({
        title: 'Confirm release',
        message: `Confirm delete'${friend.nickName}',and clear the chat history?`,
        confirmButtonColor: 'var(--chat-theme-color)',
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
      }).then(() => {
        this.$http({
          url: "/friend/delete",
          method: 'POST',
          params: {
            friendId: friend.id
          }
        }).then((data) => {
          this.$message.success("Successfully deleted friend");
          this.$store.commit("removeFriend", idx);
          this.$store.commit("removePrivateChat", friend.id);
        })
      })
    },
    onAddFriend(user) {
      this.$http({
        url: "/friend/add",
        method: "POST",
        params: {
          friendId: user.id
        }
      }).then((data) => {
        this.$message.success("Added successfully, the other party has become your friend");
        let friend = {
          id: user.id,
          nickName: user.nickName,
          headImage: user.headImage,
          online: user.online
        }
        this.$store.commit("addFriend", friend);
      })
    },
    onSendMessage(user) {
      let chat = {
        type: 'PRIVATE',
        targetId: user.id,
        showName: user.nickName,
        headImage: user.headImageThumb,
      };
      this.$store.commit("openChat", chat);
      this.$store.commit("activeChat", 0);
      this.$router.push("/home/chat");
    },
    showFullImage() {
      if (this.userInfo.headImage) {
        this.$store.commit('showFullImageBox', this.userInfo.headImage);
      }
    },
    updateFriendInfo(friend, user, index) {
      // The data in the store cannot be directly modified, a deep copy of the store's data is required
      friend = JSON.parse(JSON.stringify(friend));
      friend.headImage = user.headImageThumb;
      friend.nickName = user.nickName;
      this.$http({
        url: "/friend/update",
        method: "POST",
        data: friend
      }).then(() => {
        this.$store.commit("updateFriend", friend);
        this.$store.commit("updateChatFromFriend", user);
      })
    },
    loadUserInfo(friend, index) {
      this.$http({
        url: "/user/find",
        method: "POST",
        params: {
          id: friend.id
        }
      }).then((user) => {
        this.userInfo = user;
        this.$store.dispatch('commonData/updateCurFriendUserInfo', user)
        // If you find that your friend's avatar and nickname have changed, update them
        if (user.headImageThumb != friend.headImage ||
            user.nickName != friend.nickName) {
          this.updateFriendInfo(friend, user, index)
        }
        // new
        this.$router.push('/friend-info')
      })
    },
    onCreateGroup() {
      this.$prompt('Please input the group chat name', 'Create a group chat', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        inputPattern: /\S/,
        inputErrorMessage: 'Please input the group chat name',
        customClass: 'custom-prompt'
      }).then((o) => {
        let userInfo = this.$store.state.userStore.userInfo;
        let data = {
          name: o.value
        }
        this.$http({
          url: `/group/create?groupName=${o.value}`,
          method: 'post',
          data: data
        }).then((group) => {
          this.$store.commit("addGroup", group);
        })
      })
    },
    onActiveItemGroup(group, index) {
      console.log('Click group: ', group)
      this.$store.dispatch('commonData/updateCurGroupInfo', group)
      this.$store.commit("activeGroup", index);
      this.activeGroup = JSON.parse(JSON.stringify(group));
      // Reload group members
      this.loadGroupMembers();
    },
    onInviteMember() {
      this.showAddGroupMember = true;
    },
    onCloseAddGroupMember() {
      this.showAddGroupMember = false;
    },
    onUploadSuccess(data) {
      this.activeGroup.headImage = data.originUrl;
      this.activeGroup.headImageThumb = data.thumbUrl;
    },
    onSaveGroup() {
      this.$refs['groupForm'].validate((valid) => {
        if (valid) {
          let vo = this.activeGroup;
          this.$http({
            url: "/group/modify",
            method: "POST",
            data: vo
          }).then((group) => {
            this.$store.commit("updateGroup", group);
            this.$message.success("Modified successfully");
          })
        }
      });
    },
    onDissolve() {
      Dialog.confirm({
        title: 'Confirm dissolution',
        message: `Confirm to dissolve'${this.activeGroup.name}'?`,
        confirmButtonColor: 'var(--chat-theme-color)',
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
      }).then(() => {
        this.$http({
          url: "/group/delete",
          method: 'POST',
          params: {
            groupId: this.activeGroup.id
          }
        }).then(() => {
          this.$message.success(`Group chat ${this.activeGroup.name} has been disbanded`);
          this.$store.commit("removeGroup", this.activeGroup.id);
          this.$store.commit("removeGroupChat", this.activeGroup.id);
          this.reset();
        });
      })

    },
    onKick(member) {
      Dialog.confirm({
        title: 'Confirm removal',
        message: `Are you sure to remove member ${member.remarkNickName} from the group chat?`,
        confirmButtonColor: 'var(--chat-theme-color)',
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
      }).then(() => {
        this.$http({
          url: "/group/kick",
          method: 'POST',
          params: {
            groupId: this.activeGroup.id,
            userId: member.userId
          }
        }).then(() => {
          this.$message.success(`${member.remarkNickName} has been removed from the group chat`);
          member.quit = true;
        });
      })

    },
    onQuit() {
      Dialog.confirm({
        title: 'Confirm exit',
        message: `Confirm exit'${this.activeGroup.remarkGroupName}',and clear the chat history?`,
        confirmButtonColor: 'var(--chat-theme-color)',
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
      }).then(() => {
        this.$http({
          url: "/group/quit",
          method: 'POST',
          params: {
            groupId: this.activeGroup.id
          }
        }).then(() => {
          this.$message.success(`You have exited '${this.activeGroup.name}'`);
          this.$store.commit("removeGroup", this.activeGroup.id);
          this.$store.commit("removeGroupChat", this.activeGroup.id);
          this.reset();
        });
      })

    },
    onSendMessageGroup() {
      let chat = {
        type: 'GROUP',
        targetId: this.activeGroup.id,
        showName: this.activeGroup.remarkGroupName,
        headImage: this.activeGroup.headImage,
      };
      this.$store.commit("openChat", chat);
      this.$store.commit("activeChat", 0);
      this.$router.push("/home/chat");
    },
    loadGroupMembers() {
      this.$http({
        url: "/group/members",
        method: "POST",
        params: {
          groupId: this.activeGroup.id
        }
      }).then((members) => {
        this.groupMembers = members;
        this.$store.dispatch('commonData/updateCurGroupMembers', members)
        // this.$router.push('/group-info')
      })
    },
    reset() {
      this.activeGroup = {};
      this.groupMembers = [];
    }
  },
  computed: {
    friendStore() {
      return this.$store.state.friendStore;
    },
    isFriend() {
      return this.friendStore.friends.find((f) => f.id == this.userInfo.id);
    },
    groupStore() {
      return this.$store.state.groupStore;
    },
    ownerName() {
      let member = this.groupMembers.find((m) => m.userId == this.activeGroup.ownerId);
      return member && member.remarkNickName;
    },
    isOwner() {
      return this.activeGroup.ownerId == this.$store.state.userStore.userInfo.id;
    }
  }
}
</script>

<template>
<div class="contacts-container">
  <el-scrollbar class="friend-list-items">
    <div v-for="(friend, index) in $store.state.friendStore.friends" :key="index">
      <friend-item v-show="friend.nickName.includes($store.state.commonData.chatsSearchText)" :index="index"
                   :active="friend === $store.state.friendStore.activeFriend" @chat="onSendMessage(friend)"
                   @delete="onDelItem(friend, index)" @click.native="onActiveItemFriend(friend, index)">
      </friend-item>
    </div>
  </el-scrollbar>
  <van-tabs v-model="active" v-show="false" color="var(--chat-theme-color)" @change="onChange">
    <van-tab title="Friends" name="friend">
      <el-scrollbar class="friend-list-items">
        <div v-for="(friend, index) in $store.state.friendStore.friends" :key="index">
          <friend-item v-show="friend.nickName.includes($store.state.commonData.chatsSearchText)" :index="index"
                       :active="friend === $store.state.friendStore.activeFriend" @chat="onSendMessage(friend)"
                       @delete="onDelItem(friend, index)" @click.native="onActiveItemFriend(friend, index)">
          </friend-item>
        </div>
      </el-scrollbar>
    </van-tab>
    <van-tab title="Groups" name="group">
      <el-scrollbar class="group-list-items">
        <div v-for="(group, index) in groupStore.groups" :key="index">
          <group-item v-show="!group.quit && group.remarkGroupName.includes($store.state.commonData.chatsSearchText)" :group="group"
                      :active="group === groupStore.activeGroup" @click.native="onActiveItemGroup(group, index)">
          </group-item>
        </div>
      </el-scrollbar>
    </van-tab>
  </van-tabs>
</div>
</template>

<style scoped lang="scss">
.contacts-container {
  .van-tabs--line .van-tabs__wrap {}
  .group-list-items {}
  .friend-list-items, .group-list-items {
    margin-top: 10px;
    height: calc(100vh - 110px - 44px - 60px);
    overflow-y: auto;
  }
}
</style>